package com.itheima.service.impl;

import com.itheima.common.utils.POIUtils;
import com.itheima.mapper.OrdersettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingReturn;
import com.itheima.service.OrdersettingService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Service
public class OrdersettingServiceImpl implements OrdersettingService {

    /**
     * 上传文件
     * @param excelFile
     * @return
     */
    @Override
    public void upload(MultipartFile excelFile) {
        try {
            //取得传入参数的列表
            List<String[]> lists = POIUtils.readExcel(excelFile);

            for (String[] list : lists) {
                //准备要传入的数据
                int reservations = 0;
                String[] strings = new String[]{list[0]};
                String[] split = strings[0].split("/");
                StringJoiner datestr = new StringJoiner("-");
                for (String s : split) {
                    datestr.add(s);
                }
                String dates = datestr.toString();
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date = LocalDate.parse(dates, df);
                Integer number = Integer.valueOf(list[1]);

                ordersettingMapper.addOrderSetting(date, number, reservations);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据年月查询对应的预约设置信息
     *
     * @param month
     * @return
     */
    @Override
    public List<OrderSettingReturn> getOrderSettingByMonth(String month) {
        //从日期中拿出年月信息并获取年月区间LocalDate
        String[] split = month.split("-");
        //拼接begin和end的日期对象
        String begin = parseDateString(split,1);
        String end = "";
        switch(split[1])
        {
            case "2":{
                int year = Integer.valueOf(split[0]);
                if((year % 4 == 0 && year % 100 != 0 )||year % 40 == 0){
                    end = parseDateString(split,29);
                }
                else end = parseDateString(split,28);
                break;
            }
            case "1":{
                end = parseDateString(split,31);
                break;
            }case "3":{
                end = parseDateString(split,31);
                break;
            }case "5":{
                end = parseDateString(split,31);
                break;
            }case "7":{
                end = parseDateString(split,31);
                break;
            }case "8":{
                end = parseDateString(split,31);
                break;
            }case "10":{
                end = parseDateString(split,31);
                break;
            }case "12":{
                end = parseDateString(split,31);
                break;
            }case "4":{
                end = parseDateString(split,30);
                break;
            }case "6":{
                end = parseDateString(split,30);
                break;
            }case "9":{
                end = parseDateString(split,30);
                break;
            }case "11":{
                end = parseDateString(split,30);
                break;
            }
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate begintime = LocalDate.parse(begin, df);
        LocalDate endtime = LocalDate.parse(end, df);
        //获取并返回
        List<OrderSettingReturn> list = ordersettingMapper.getOrderSettingByMonth(begintime,endtime);
        return list;
    }

    /**
     * 下载文件模板
     *
     * @param filename
     * @param response
     * @return
     */
    @Override
    public void downloadTemplate(String filename, HttpServletResponse response) throws IOException {
        //指定文件类型为excel
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename="+filename);
        //查询到的数据通过poi写入到excel文件中
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(stream);
        ServletOutputStream os = response.getOutputStream();
        excel.write(os);
        os.close();
        excel.close();
        stream.close();
    }

    /**
     * 将年月转化为yyyy-MM-dd字符串
     * @param split
     * @param i
     * @return
     */
    private String parseDateString(String[] split, int i) {
        StringJoiner stringJoiner = new StringJoiner("-");
        stringJoiner.add(split[0]);
        if(Integer.valueOf(split[1]) < 10){
            stringJoiner.add("0" + split[1]);
        }
        else stringJoiner.add(split[1]);
        if(i < 10)
        stringJoiner.add( "0" + String.valueOf(i));
        else
        stringJoiner.add(String.valueOf(i));
        return stringJoiner.toString();
    }

    @Autowired
    private OrdersettingMapper ordersettingMapper;

    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @Override
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        Date date = orderSetting.getOrderDate();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();

        int number = orderSetting.getNumber();
        ordersettingMapper.editNumberByOrderDate(number,localDate);
    }
}
